package com.jida.tijian.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jida.tijian.domain.Users;
import com.jida.tijian.dto.ResponseObject;
import com.jida.tijian.service.UsersService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController  //@Controller+@ResponseBody  所以后端接口给回前端的数据也都是json对象
public class UserController {

    @Autowired
    UsersService usersService;

    //    接受/login的请求
    @RequestMapping("/login")  //http://localhost:8080/login
/// /    RequestBody 是将前端传送的参数（JOSON）转成数据对象
/// /当前端通过 POST、PUT 等方法发送请求时，通常会将数据放在 请求体（Request Body） 中
    public ResponseObject<Users> login(@RequestBody Users users, HttpServletResponse response) throws JsonProcessingException {   //json对象-->java对象
        System.out.println("controller");
        System.out.println("users:" + users.getUserId() + "," + users.getPassword());

        //创建返回给前端的对象
        ResponseObject<Users> responseObject;
        //调用userService的login方法并且传入 users
        responseObject = usersService.login(users);
        if (response.getStatus() == (ResponseObject.SUCCESS_STATUS)) {
            Map<String, Object> map = new HashMap<>();
            //map.put("currentUser",user);
            map.put("currentUser", new ObjectMapper().writeValueAsString(users));

            JwtBuilder builder = Jwts.builder()
                    .setId(UUID.randomUUID().toString())
                    .setIssuedAt(new Date())
                    .signWith(SignatureAlgorithm.HS256, "123456-----")    //随便写，越长越好
                    .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 20))     //改成3，方便测试
                    .setClaims(map).setSubject(users.getUserId());
            String key = builder.compact();
            response.setHeader("token", key);
            System.out.println("返回数据给前端。。。。。。。。。。。。。。");

            return responseObject;
        }

        //压的数据：users
        return responseObject;
    }
}

//package com.jida.tijian.controller;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.jida.tijian.domain.Users;
//import com.jida.tijian.dto.ResponseObject;
//import com.jida.tijian.service.UsersService;
//import io.jsonwebtoken.JwtBuilder;
//import io.jsonwebtoken.Jwts;
//import io.jsonwebtoken.SignatureAlgorithm;
/// /import jdk.nashorn.internal.parser.JSONParser;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.UUID;
//
//@RestController  //  @Controller+@ResponseBody  表示当前类是一个servlet 同时接口返回数据都是json字符串
/// /@CrossOrigin(origins = "*",exposedHeaders = "token",allowedHeaders = "*")
//public class UserController {
//    @Autowired
//    UsersService usersService;
//
//    /**
//     * 处理前端注册功能的接口方法
//     */
/// /    @RequestMapping("register")     //那么前端递交请求，路径就是/register  这样就会交给我们这个方法来处理
/// /    public ResponseObject register(@RequestBody Users users){  //前端与后端都是ajax交互，传递的是json字符串，  @RequestBody注解可以把json字符串转化成java对象
/// /        return usersService.registerService(users);
/// /    }
//
//    /**
//     * 处理前端登录功能的接口方法
//     */
//    @RequestMapping("login")
//    public ResponseObject login(@RequestBody Users users, HttpServletResponse response) throws JsonProcessingException {
//
//        System.out.println("进入UserController login方法。。。。。。。。。。。。。。。。");
//        ResponseObject apiResponse = usersService.login(users);
//        Users user = (Users) apiResponse.getData();
//        if (apiResponse.getStatus().equals(ResponseObject.SUCCESS_STATUS)) {
//            Map<String, Object> map = new HashMap<>();
//            //map.put("currentUser",user);
//            map.put("currentUser", new ObjectMapper().writeValueAsString(user));
//
//            JwtBuilder builder = Jwts.builder()
//                    .setId(UUID.randomUUID().toString())
//                    .setIssuedAt(new Date())
//                    .signWith(SignatureAlgorithm.HS256, "123456-----")    //随便写，越长越好
//                    .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 20))     //改成3，方便测试
//                    .setClaims(map).setSubject(user.getUserId());
//            String key = builder.compact();
//            response.setHeader("token", key);
//            System.out.println("返回数据给前端。。。。。。。。。。。。。。");
//
//            return apiResponse;
//        }
//        //压的数据：users
//        return apiResponse;
//    }
//}
//    定义处理注册请求的方法

//    定义处理修改密码的方法

//    定义处理快捷登录请求的方法



